package com.nattakute.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.nattakute.dao.UserDAO;
import com.nattakute.model.Role;
import com.nattakute.model.UserStatus;
import com.nattakute.model.Users;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserDAO userDao;

	@SuppressWarnings("unused")
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		Users user = userDao.getUserByName(username);
		String password = user.getPassword();
		if(user!=null){
			boolean enable = user.getStatus().equals(UserStatus.ACTIVE);
			boolean accountNonExpired = user.getStatus().equals(
					UserStatus.ACTIVE);
			boolean credentialsNonExpired = user.getStatus().equals(
					UserStatus.ACTIVE);
			boolean accountNonLocked = user.getStatus().equals(
					UserStatus.ACTIVE);

			Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

			for (Role role : user.getRoles()) {
				authorities.add(new GrantedAuthorityImpl(role.getRoleName()));
			}
			org.springframework.security.core.userdetails.User securityUser =new 
					org.springframework.security.core.userdetails.User(username, password, authorities);
			return securityUser;
		}
		else {
			throw new UsernameNotFoundException("User not found!!");
		}
	}
}
